import { app, BrowserWindow, ipcMain } from 'electron'
import '../renderer/store'

/**
 * Set `__static` path to static files in production
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-static-assets.html
 */
if (process.env.NODE_ENV !== 'development') {
  global.__static = require('path').join(__dirname, '/static').replace(/\\/g, '\\\\')
}

let mainWindow
const winURL = process.env.NODE_ENV === 'development'
  ? `http://localhost:9080`
  : `file://${__dirname}/index.html`

function createWindow () {
  /**
   * Initial window options
   */
  mainWindow = new BrowserWindow({
    height: 800,
    useContentSize: true,
    width: 1200,
    frame: false,
    resizable: false,
    skipTaskbar: false,
    transparent: false,
    autoHideMenuBar: true,
    webPreferences: {
      webSecurity: false,
      nodeIntegration: true
    },
    // 支持webview
    webviewTag: true
  })

  let newWin = {}
  ipcMain.on('newwindow',function(event, arg){
    let win = newWin[arg.command+arg.id]
    if(win){
      win.focus() // 存在 则聚焦
      return
    }
    win = new BrowserWindow({
      width:1200,
      height:700,
      minWidth:900,
      minHeight:620,
      frame:true,//是否显示边缘框
      fullscreen:false, //是否全屏显示
      useContentSize: true,//使用web网页size
      title:"项目名",
      autoHideMenuBar:true,
      webPreferences: {
        webSecurity: false,
        nodeIntegration: true
      },
      // 支持webview
      webviewTag: true
    })
    win.loadURL(winURL+'#/serverLogs?serverId='+arg.id + '&command=' + arg.command + '&host='+ arg.host)  // 此处写 你要打开的路由地址
    win.on('close',()=>{
      win=null
      newWin[arg.command+arg.id] = null
    })
    newWin[arg.command+arg.id] = win
  })

  mainWindow.loadURL(winURL)

  mainWindow.on('closed', () => {
    for (const key in newWin) {
      let win = newWin[key]
      if (win) {
        win.close()
      }
      win = null
    }
    mainWindow = null
  })
}

app.on('ready', createWindow)

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (mainWindow === null) {
    createWindow()
  }
})

ipcMain.on('close',e=>{
  mainWindow.close()
})
ipcMain.on('minimize',e=>{
  mainWindow.minimize()
})


/**
 * Auto Updater
 *
 * Uncomment the following code below and install `electron-updater` to
 * support auto updating. Code Signing with a valid certificate is required.
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-electron-builder.html#auto-updating
 */

/*
import { autoUpdater } from 'electron-updater'

autoUpdater.on('update-downloaded', () => {
  autoUpdater.quitAndInstall()
})

app.on('ready', () => {
  if (process.env.NODE_ENV === 'production') autoUpdater.checkForUpdates()
})
 */
